package com.eightywork.life.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.activity.NoticeListActivity.NoticeList;
import com.eightywork.life.adapter.MsgListAdapter;
import com.eightywork.life.adapter.PmListAdapter;
import com.eightywork.life.model.Notice;
import com.eightywork.life.model.Pm;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.FooterView;
import com.eightywork.life.widget.MyListView;
import com.eightywork.life.widget.MyListView.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;

public class MsgListActivity extends BaseActivity implements OnClickListener {
	private ImageButton backButton, postButton;
	private MyListView listView;
	private TextView headerTitle;
	private boolean isLoading, isRefresh = false;
	private AsyncTask<?, ?, ?> noticeListTask, pmListTask;
	private MsgListAdapter adapter;
	private List<Map<String, Object>> mListItems = new ArrayList<Map<String,Object>>();
	public static List<Pm> plist = new ArrayList<Pm>();
	public static List<Notice> nlist = new ArrayList<Notice>();
	private int page = 1;
	private int flag = 0;
	private FooterView footView;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_msg_list);
		initView();
		initData();
		getList();
		JPushInterface.clearAllNotifications(context);
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}

	@Override
	public void onDestroy() {
		if (noticeListTask != null)
			noticeListTask.cancel(true);
		if (pmListTask != null)
			pmListTask.cancel(true);
		super.onDestroy();
	}
	
	private void initView() {
		
		headerTitle = (TextView) findViewById(R.id.header_title);
		backButton = (ImageButton) findViewById(R.id.button_back);
		postButton = (ImageButton) findViewById(R.id.button_right);
		listView = (MyListView) findViewById(R.id.listView_msg);
		footView = new FooterView(this);
		footView.hideAll();
		backButton.setOnClickListener(this);
		postButton.setOnClickListener(this);
		
	}
	
	private void initData() {
		initHeader("未读消息");
		adapter = new MsgListAdapter(context, null);
		listView.setAdapter(adapter);
		listView.setonRefreshListener(new OnRefreshListener() {		
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				page = (flag == 0)? 1: 0;
				isLoading = false;
				isRefresh = true;
				getList();
				
			}
		});
		
		//getList();
		
	}
	
	private void getList() {
		//noticeListTask = new NoticeList().execute();
		pmListTask = new PmListTask().execute();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if ( v == backButton) {
			Intent intent = new Intent(context, IndexActivity.class);
			context.startActivity(intent);
			 overridePendingTransition(R.anim.push_left_in,R.anim.push_right_out);
			finish();
		} else if (v == postButton) {
			Intent intent = new Intent(MsgListActivity.this, SelectNeighbourActivity.class);
			startActivity(intent);
		}
	}
	
	class PmListTask extends AsyncTask<Void, Void, String> {
		List<Pm> plist;
		List<Notice> nlist;
		Map<String, Object> item;
		List<Map<String, Object>> pdata = null;
		List<Map<String, Object>> ndata = null;
		List<Map<String, Object>> data = null;
		@Override
		protected void onPreExecute() {
			isLoading = true;
			if (flag == 0) {
				showProgressDialog("正在加载中...");
			} else {
				page++;
			}
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				nlist = SpaceService.notice(page + "", "");
				plist = SpaceService.pm(page + "", "");
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				showMessage(e.getErrorMessage());
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			isLoading = false;
			if (flag == 0) {
				hideProgressDialog(); 
			}
			if (isRefresh) {	
				listView.onRefreshComplete();
			} 
			if (plist != null || nlist != null) {
				data = new ArrayList<Map<String,Object>>();
				if (plist != null) {
					pdata = new ArrayList<Map<String, Object>>();
					for (int i = 0; i < plist.size(); i++) {
						Pm pm = plist.get(i);
						if (pm.getIsnew().equals("1")) {
							item = new HashMap<String, Object>();
							item.put("mark", "pm");
							item.put("authorname", pm.getToname());
							item.put("toavatar", pm.getToavatar());
							item.put("toVerity_type", pm.getToverify_type());
							item.put("touid", pm.getTouid());
							item.put("message", pm.getMessage()); 
							pdata.add(item); 
						}			
					}
					data.addAll(pdata);
				}
				if (nlist != null) {
					ndata = new ArrayList<Map<String, Object>>();
					for (int i = 0; i < nlist.size(); i++) {
						Notice noti = nlist.get(i);
						if (noti.getIsnew().equals("1")) {
							item = new HashMap<String, Object>();
							item.put("mark", "notice");
							item.put("authorname", noti.getAuthorname());
							item.put("note", noti.getNote());
							item.put("id", noti.getSid());
							item.put("authoravatar", noti.getAuthoravatar());
							item.put("verify_type", noti.getAuthorverifyType());
							item.put("noteurl", noti.getNoteurl());
							item.put("type", noti.getType());
							item.put("idtype", noti.getIdtype());
							item.put("uid", noti.getAuthoruid());
							ndata.add(item); 
						}			
					}
					data.addAll(ndata);
				}
			}
			
			
			
			if (data != null && data.size() > 0) {
				if (flag == 0) {
					adapter = new MsgListAdapter(context, data);
					listView.addFooterView(footView.getFooter());
					listView.setAdapter(adapter);
					listView.setOnScrollListener(new ScrollListener());
					mListItems = data;
					flag = 1;
				} else if (isRefresh) {
					isRefresh = false;
					adapter = new MsgListAdapter(context, data);				
					listView.setAdapter(adapter);
					listView.setOnScrollListener(new ScrollListener());
					mListItems = data;
					listView.onRefreshComplete();
				} else {
					mListItems.addAll(data);
					adapter.notifyDataSetChanged();
				}
				if (data.size() < 5) {
					footView.showNoData();
				}
			} else {
				if (data != null) {
					if (flag == 0) {
						listView.addFooterView(footView.getFooter());
					}
					footView.showNoData();				
				} else {
					footView.hideAll();
					showMessage("网络链接失败，请稍后重试！");
				}
				
			}				
			
			/*
			if (result == null) {
				if (isRefresh) {
					isRefresh = false;
					mListItems.clear();
					listView.onRefreshComplete();
				} 
				else {
					
				}
				if (plist != null) {
					for (int i = 0; i < plist.size(); i++) {
						Pm pm = plist.get(i);
						if (pm.getIsnew().equals("1")) {
							item = new HashMap<String, Object>();
							item.put("mark", "pm");
							item.put("authorname", pm.getToname());
							item.put("toavatar", pm.getToavatar());
							item.put("toVerity_type", pm.getToverify_type());
							item.put("touid", pm.getTouid());
							item.put("message", pm.getMessage()); 
							pdata.add(item); 
						}			
					}		
				}
				if (nlist != null) {
//					list.addAll(nlist);
					for (int i = 0; i < nlist.size(); i++) {
						Notice noti = nlist.get(i);
						if (noti.getIsnew().equals("1")) {
							item = new HashMap<String, Object>();
							item.put("mark", "notice");
							item.put("authorname", noti.getAuthorname());
							item.put("note", noti.getNote());
							item.put("authoravatar", noti.getAuthoravatar());
							item.put("verify_type", noti.getAuthorverifyType());
							item.put("noteurl", noti.getNoteurl());
							ndata.add(item); 
						}			
					}
					
				}
				mListItems.addAll(ndata);
				mListItems.addAll(pdata);
				adapter.notifyDataSetChanged();
				
			} else {
				showMessage(result);
			}
			page++;

			isLoading = false;
			super.onPostExecute(result);
			*/
			
		}
		
	}
	
	private class ScrollListener implements OnScrollListener
	{
		private int listViewLastItem = 0;
		private boolean isOver = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			if (adapter.getCount() % page > 0 || adapter.getCount() == 0)
			{
				footView.hideAll();
				isOver = true;
			}
			listViewLastItem = firstVisibleItem + visibleItemCount - 1; 
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{    
			if (!isOver && !isLoading && listViewLastItem >= adapter.getCount()-5 
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				footView.showLoading();
				pmListTask = new PmListTask().execute();
			}

		}
	}

}
